<script setup>
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据列表
const livestockList = ref([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100]
})

// 搜索条件
const searchForm = reactive({
  earSignal: '',
  electronicEarTag: '',
  variety: null,
  geneRank: null,
  fatherNumber: null,
  motherNumber: null,
  dateofBirth: null,
  entryDate: null,
  placeOfBirth: null,
  birthWeight: null,
  note: ''
})

// 下拉选项
const varietyOptions = [
  { id: 1, name: '萨福克' },
  { id: 2, name: '多赛特' },
  { id: 3, name: '美利奴' },
  { id: 4, name: '波尔山羊' },
  { id: 5, name: '其他' }
]

const geneLevelOptions = [
  { id: 1, name: '优秀' },
  { id: 2, name: '良好' },
  { id: 3, name: '一般' },
  { id: 4, name: '较差' }
]

// 获取列表数据
const fetchLivestockList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await Reads.get('/Management/GetEweFilesPaged', { params })
    
    if (response.data && response.data.code === 400) {
      console.log(response)
      livestockList.value = response.data.data?.data || []
      pagination.total = response.data.data?.totalCount || 0
    } else {
      alert('获取列表失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取牲畜列表失败:', error)
    alert('获取列表失败：' + (error.response?.data?.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchLivestockList()
}

// 重置搜索
const handleReset = () => {
  searchForm.earSignal = ''
  searchForm.electronicEarTag = ''
  searchForm.variety = null
  searchForm.geneRank = null
  searchForm.fatherNumber = null
  searchForm.motherNumber = null
  searchForm.dateofBirth = null
  searchForm.entryDate = null
  searchForm.placeOfBirth = null
  searchForm.birthWeight = null
  searchForm.note = ''
  handleSearch()
}

// 分页处理
const handlePageChange = (page) => {
  pagination.currentPage = page
  fetchLivestockList()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchLivestockList()
}

// 编辑
const handleEdit = (row) => {
  router.push({
    name: 'livestock-edit',
    params: {
      id: row.eweId
    }
  })
}

// 删除
const handleDelete = async (row) => {
  console.log(row.eweId);
  if (!confirm(`确定要删除耳号为 "${row.earSignal}" 的牲畜吗？`)) {
    return
  }

  try {
    const response = await Writes.delete(`/Management/DeleteEweFile`, {
      data: {
        eweId: row.eweId
      }
    })
    
    if (response.data && response.data.code === 200) {
      alert('删除成功！')
      fetchLivestockList()
    } else {
      alert('删除失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    console.error('删除牲畜失败:', error)
    alert('删除失败：' + (error.response?.data?.message || '网络错误'))
  }
}

//#region 格式化显示函数
// 格式化显示函数
const formatvariety = (value) => {
  const option = varietyOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatgeneLevel = (value) => {
  const option = geneLevelOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

//#endregion



// 组件挂载时获取数据
onMounted(() => {
  fetchLivestockList()
})
</script>

<template>
  <div class="livestock-list-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <form class="search-form">
        <div class="form-row">
          <div class="form-group">
            <label for="earSignal">耳号</label>
            <input
              id="earSignal"
              v-model="searchForm.earSignal"
              type="text"
              class="form-control"
              placeholder="请输入耳号"
              @keyup.enter="handleSearch"
            >
          </div>
          <div class="form-group">
            <label for="electronicEarTag">电子耳标号</label>
            <input
              id="electronicEarTag"
              v-model="searchForm.electronicEarTag"
              type="text"
              class="form-control"
              placeholder="请输入电子耳标号"
              @keyup.enter="handleSearch"
            >
          </div>
          <div class="form-group">
            <label for="variety">品种</label>
            <select id="variety" v-model="searchForm.variety" class="form-control">
              <option value="">请选择品种</option>
              <option v-for="option in varietyOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="geneRank">基因等级</label>
            <select id="geneRank" v-model="searchForm.geneRank" class="form-control">
              <option value="">请选择基因等级</option>
              <option v-for="option in geneLevelOptions" :key="option.id" :value="option.id">{{ option.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label for="fatherNumber">父耳号</label>
            <input
              id="fatherNumber"
              v-model="searchForm.fatherNumber"
              type="text"
              class="form-control"
              placeholder="请输入父耳号"
            >
          </div>
          <div class="form-group">
            <label for="motherNumber">母耳号</label>
            <input
              id="motherNumber"
              v-model="searchForm.motherNumber"
              type="text"
              class="form-control"
              placeholder="请输入母耳号"
            >
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="dateofBirth">出生日期</label>
            <input
              id="dateofBirth"
              v-model="searchForm.dateofBirth"
              type="date"
              class="form-control"
            >
          </div>
          <div class="form-group">
            <label for="entryDate">入场日期</label>
            <input
              id="entryDate"
              v-model="searchForm.entryDate"
              type="date"
              class="form-control"
            >
          </div>
          <div class="form-group">
            <label for="placeOfBirth">出生场地</label>
            <input
              id="placeOfBirth"
              v-model="searchForm.placeOfBirth"
              type="text"
              class="form-control"
              placeholder="请输入出生场地"
            >
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="birthWeight">出生重量</label>
            <input
              id="birthWeight"
              v-model="searchForm.birthWeight"
              type="text"
              class="form-control"
              placeholder="请输入出生重量"
            >
          </div>
          <div class="form-group">
            <label for="note">备注</label>
            <input
              id="note"
              v-model="searchForm.note"
              type="text"
              class="form-control"
              placeholder="请输入备注"
            >
          </div>
          <div class="form-group">
            <label>&nbsp;</label>
            <div class="button-group-right">
              <button type="button" class="btn btn-primary" @click="handleSearch" :disabled="loading">
                搜索
              </button>
              <button type="button" class="btn btn-secondary" @click="handleReset">
                重置
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="livestockList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="earSignal" label="耳号" width="120" align="center" />
        <el-table-column prop="electronicEarTag" label="电子耳标号" width="140" align="center" />
        <el-table-column prop="variety" label="品种" width="100" align="center">
          <template #default="{ row }">
            {{ formatvariety(row.variety) }}
          </template>
        </el-table-column>
        <el-table-column prop="geneRank" label="基因等级" width="100" align="center">
          <template #default="{ row }">
            {{ formatgeneLevel(row.geneRank) }}
          </template>
        </el-table-column>
        <el-table-column prop="fatherNumber" label="父耳号" width="120" align="center" />
        <el-table-column prop="motherNumber" label="母耳号" width="120" align="center" />
        <el-table-column prop="dateofBirth" label="出生日期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.dateofBirth) }}
          </template>
        </el-table-column>
        <el-table-column prop="entryDate" label="入场日期" width="120" align="center">
          <template #default="{ row }">
            {{ formatDate(row.entryDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="placeOfBirth" label="出生场地" width="120" align="center" />
        <el-table-column prop="birthWeight" label="出生重量(kg)" width="120" align="center" />
        <el-table-column prop="note" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="pagination.pageSizes"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.livestock-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.btn-icon {
  width: 16px;
  height: 16px;
}

/* 搜索区域样式 - 完全匹配DescendantFromView.vue风格 */
.search-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

.form-group.button-group {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  gap: 10px;
}

.button-group-right {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: flex-end;
  height: 38px;
}

.form-control {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s ease;
  width: 100%;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-control::placeholder {
  color: #999;
}

select.form-control {
  cursor: pointer;
  height: 38px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: bold !important;
  border-bottom: 2px solid #e4e7ed !important;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-button--small) {
  padding: 7px 15px;
  font-size: 12px;
  border-radius: 4px;
}

:deep(.el-pagination) {
  justify-content: center;
}
</style>